//
//  SHAppDelegate.m
//  youjian03
//
//  Created by 常琼 on 14/10/8.
//  Copyright (c) 2014年 com.shouhuobao. All rights reserved.
//

#import "SHAppDelegate.h"
#import "UMSocial.h"
// 支付宝
#import "AlixPayResult.h"
#import "DataVerifier.h"

//友盟统计
#import "MobClick.h"

#import "UMFeedback.h"
#import "UMessage.h"
#import "SDWebImageManager+MJ.h"
#import "SDWebImageManager.h"


@interface SHAppDelegate()
@property (nonatomic,copy) NSString *phone;

@end


@implementation SHAppDelegate



- (void)umengTrack {
    //    [MobClick setCrashReportEnabled:NO]; // 如果不需要捕捉异常，注释掉此行
    //TODO:注意Release发布时需要注释掉此行
    [MobClick setLogEnabled:YES];  // 打开友盟sdk调试，,减少io消耗
    [MobClick setAppVersion:XcodeAppVersion]; //参数为NSString * 类型,自定义app版本信息，如果不设置，默认从CFBundleVersion里取
    //
    [MobClick startWithAppkey:YMAPPID reportPolicy:(ReportPolicy) REALTIME channelId:nil];
    //   reportPolicy为枚举类型,可以为 REALTIME, BATCH,SENDDAILY,SENDWIFIONLY几种
    //   channelId 为NSString * 类型，channelId 为nil或@""时,默认会被被当作@"App Store"渠道
    
    //      [MobClick checkUpdate];   //自动更新检查, 如果需要自定义更新请使用下面的方法,需要接收一个(NSDictionary *)appInfo的参数
    //    [MobClick checkUpdateWithDelegate:self selector:@selector(updateMethod:)];
    
    [MobClick updateOnlineConfig];  //在线参数配置
    
    //    1.6.8之前的初始化方法
    //    [MobClick setDelegate:self reportPolicy:REALTIME];  //建议使用新方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onlineConfigCallBack:) name:UMOnlineConfigDidFinishedNotification object:nil];
    
}

- (void)onlineConfigCallBack:(NSNotification *)note {
    
    HMLog(@"online config has fininshed and note = %@", note.userInfo);
}



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    [self umengTrack];
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
        [[NSUserDefaults standardUserDefaults] setObject:[OpenUDID value] forKey:@"SHOPEN_UDID"];
        //第一次  启动
        // 1.获得数据库文件的路径
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filename = [doc stringByAppendingPathComponent:@"youjian.sqlite"];
        
        // 2.得到数据库
        FMDatabase *db = [FMDatabase databaseWithPath:filename];
        
        // 3.打开数据库
        if ([db open]) {
            // 4.创表
            BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS userinfo (id integer PRIMARY KEY AUTOINCREMENT,  phone text NOT NULL,token text NOT NULL);"];
//            id,phone,token
            if (result) {
               
            } else {
               
            }
        }
        
    }
    
    else{
        //不是第一次
        // 1.获得数据库文件的路径
        [[NSUserDefaults standardUserDefaults] setObject:[OpenUDID value] forKey:@"SHOPEN_UDID"];
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filename = [doc stringByAppendingPathComponent:@"youjian.sqlite"];
        
        // 2.得到数据库
        FMDatabase *db = [FMDatabase databaseWithPath:filename];
        if([db open])
        {
            FMResultSet *resultset =  [db executeQuery:@"select * from userinfo"];
           while ([resultset next]) {
               NSString *phoneno = [resultset stringForColumn:@"phone"];
               
             
               self.phone = phoneno;
           }
        }
        if (self.phone==nil)
        {
           
        }
        else
        {
          
        }
    }
    //反馈
 
    //集成信息
    
    Class cls = NSClassFromString(@"UMANUtil");
    SEL deviceIDSelector = @selector(openUDIDString);
    NSString *deviceID = nil;
    if(cls && [cls respondsToSelector:deviceIDSelector]){
        deviceID = [cls performSelector:deviceIDSelector];
    }
    
    NSLog(@"kaka:{\"oid\": \"%@\"}", deviceID);
    
    
    
    [UMFeedback setAppkey:YMAPPID];
    [UMFeedback setLogEnabled:YES];
    
    
    // with remote push notification
    [UMessage startWithAppkey:YMAPPID launchOptions:launchOptions];
    if (IOS8) {
        //register remoteNotification types
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
    } else {
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge |
         UIRemoteNotificationTypeSound |
         UIRemoteNotificationTypeAlert];
    }
    [UMessage setLogEnabled:NO];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(checkFinished:)
                                                 name:UMFBCheckFinishedNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveNotification:)
                                                 name:nil
                                               object:nil];
    
    NSDictionary *notificationDict = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    [UMFeedback didReceiveRemoteNotification:notificationDict];

    
    return YES;
}

- (void)receiveNotification:(id)receiveNotification {
    //    NSLog(@"receiveNotification = %@", receiveNotification);
}

- (void)checkFinished:(NSNotification *)notification {
    NSLog(@"class checkFinished = %@", notification);
}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    [self parse:url application:application];
    return  [UMSocialSnsService handleOpenURL:url];
}
- (void)parse:(NSURL *)url application:(UIApplication *)application {
    
       //结果处理
       AlixPayResult* result = [self handleOpenURL:url];
    
    
        /*
         *用公钥验证签名 严格验证请使用result.resultString与result.signString验签
         */
       NSDictionary *dic = @{@"key":[NSString stringWithFormat:@"%d",result.statusCode]};

        [[NSNotificationCenter defaultCenter] postNotificationName:FHJG object:nil userInfo:dic];

        
        //交易成功
//        NSString* key =  PUBLIC_KEY;
//        			id<DataVerifier> verifier;
//                    verifier = CreateRSADataVerifier(key);
//        
//        			if ([verifier verifyString:result.resultString withSign:result.signString])
//                    {
//                        //验证签名成功，交易结果无篡改
//                        HMLog(@"成功");
//        			}
        
    
}

#pragma mark - Remote Notification

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [UMessage registerDeviceToken:deviceToken];
     NSLog(@"umeng message alias is: %@", [UMFeedback uuid]);
    [UMessage addAlias:[UMFeedback uuid] type:@"umeng_feedback" response:^(id responseObject, NSError *error) {
        if (error != nil) {
            NSLog(@"%@", error);
            NSLog(@"%@", responseObject);
        }
    }];
}


- (AlixPayResult *)resultFromURL:(NSURL *)url {
    NSString * query = [[url query] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
#if ! __has_feature(objc_arc)
    return [[[AlixPayResult alloc] initWithString:query] autorelease];
#else
    return [[AlixPayResult alloc] initWithString:query];
    
#endif
}

- (AlixPayResult *)handleOpenURL:(NSURL *)url {
    AlixPayResult * result = nil;
    
    if (url != nil && [[url host] compare:@"safepay"] == 0) {
        result = [self resultFromURL:url];
    }
    
    return result;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    
    
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{

    
    
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{

    
}

- (void)applicationWillTerminate:(UIApplication *)application
{
 
    
}


- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    [[SDWebImageManager sharedManager] cancelAll];
    [[SDImageCache sharedImageCache] clearMemory];
}


@end
